﻿#include <stdafx.h>
#include <stdio.h>
#include <algorithm>
#include "audio_processing.h"

#define VOLUMEMAX  32767

namespace audio_tools
{
float GetVolumeByDsound(int volume)
{
    if (volume > 0)
    {
        return 1.0;
    }
    else if (volume < -5000)
    {
        return 0;
    }
    float voluem_temp = volume * 1.0 / 2000;
    float single_v = pow(10, voluem_temp);
    return single_v;
}
int GetStreamVolume(const int16_t *play_frm, int length)
{
    double rms = 0;

    for (int i = 0; i < length; i++)
    {
        int32_t block = play_frm[i];
        rms += block * block;
    }
    rms /= length;
    int ret = sqrt(rms);
    return ret;
}
//获取音量大小,算术平均
int GetPcmVolume(const int16_t *play_frm, int length)
{
    int rms = 0;

    for (int i = 0; i < length; i++)
    {
        rms += abs(play_frm[i]);
    }
    rms /= length;
    return rms;
}
//获取音量大小,分贝
int GetPcmDb(const int16_t *play_frm, int length)
{
#if 0
    double rms = 0;
    for (int i = 0; i < length; i++)
    {
        rms += abs(play_frm[i]);
    }
    rms /= length;
    int ret = 0;
    if (rms > 1) {
        ret = (int)(20.0*log10((double)rms / 65535.0)) + 96;
    }
    return ret;
#else
    int16_t ret = 0;
    int sum = 0;
    int16_t* pos = (int16_t *)play_frm;
    for (int i = 0; i < length; i++) {
        sum += abs(*pos);
        pos++;
    }
    ret = sum * 500.0 / (length * VOLUMEMAX);
    if (ret >= 100){
        ret = 100;
    }
    return ret;
#endif
}

}  // namespace audio_tools
